package com.example.partyfee.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.partyfee.dto.PartyMemberDTO;
import com.example.partyfee.dto.PartyMemberQueryDTO;
import com.example.partyfee.dto.Result;
import com.example.partyfee.entity.PartyMember;
import com.example.partyfee.service.PartyMemberService;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/party-members")
@RequiredArgsConstructor
public class PartyMemberController {

    private final PartyMemberService partyMemberService;

    @PostMapping
    @PreAuthorize("hasRole('ADMIN')")
    public Result<Void> createPartyMember(@Valid @RequestBody PartyMemberDTO partyMemberDTO) {
        partyMemberService.createPartyMember(partyMemberDTO);
        return Result.success();
    }

    @PutMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<Void> updatePartyMember(@PathVariable Long id, @Valid @RequestBody PartyMemberDTO partyMemberDTO) {
        partyMemberService.updatePartyMember(id, partyMemberDTO);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<Void> deletePartyMember(@PathVariable Long id) {
        partyMemberService.deletePartyMember(id);
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result<PartyMember> getPartyMember(@PathVariable Long id) {
        return Result.success(partyMemberService.getPartyMember(id));
    }

    @GetMapping
    public Result<IPage<PartyMember>> getPartyMemberPage(PartyMemberQueryDTO queryDTO) {
        return Result.success(partyMemberService.getPartyMemberPage(queryDTO));
    }

    @PostMapping("/import")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<List<String>> importPartyMembers(@RequestParam("file") MultipartFile file) throws IOException {
        List<String> errors = partyMemberService.importPartyMembersFromExcel(file);
        if (errors.isEmpty()) {
            return Result.success("导入成功", null);
        } else {
            return Result.success("导入过程中存在错误", errors);
        }
    }

    @GetMapping("/export")
    public void exportPartyMembers(PartyMemberQueryDTO queryDTO, HttpServletResponse response) throws IOException {
        partyMemberService.exportPartyMembersToExcel(queryDTO, response);
    }
} 